package pshop.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pshop.servlet.util.BestellUtils;
import pshop.servlet.util.SessionUtils;
import pshop.servlet.util.WkUtils;

public class PShopServlet extends HttpServlet {
	private static final long serialVersionUID = 6518971713069656429L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		work(req, resp);
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		work(req, resp);
	}

	public void work(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		String action = (String) req
				.getParameter(ServletConstants.PARAM_ACTION);
		// String referer = req.getHeader("Referer");
		// Map<String, List<String>> refParams =
		// URLUtils.getQueryParams(referer);
		// String refererAction =
		// refParams.containsKey(ServletConstants.PARAM_ACTION)?refParams.get(ServletConstants.PARAM_ACTION).get(0):null;

		String forward = "index.jsp";

		if (ServletConstants.PARAM_ACTION_ADD.equals(action)
				|| ServletConstants.PARAM_ACTION_REMOVE.equals(action)
				|| ServletConstants.PARAM_ACTION_DELETE.equals(action)) {
			WkUtils.updateWk(req, action);
			forward = "wk-view.jsp";
		} else if (ServletConstants.PARAM_ACTION_SHOW_WK.equals(action)) {
			forward = "wk-view.jsp";
		} else if (ServletConstants.PARAM_ACTION_ORDER.equals(action)) {
			BestellUtils.order(req);
			forward = "bestellen.jsp";
		} else if (ServletConstants.PARAM_ACTION_CONFRIM.equals(action)) {
			forward = BestellUtils.confirm(req);
		} else if (ServletConstants.PARAM_ACTION_SEND_ORDER.equals(action)) {
			BestellUtils.sendOrder(req);
			forward = "best-abschicken.jsp";
		} else if (ServletConstants.PARAM_ACTION_AGB.equals(action)
				|| ServletConstants.PARAM_ACTION_IMPRESSUM.equals(action)) {
			forward = action + ".jsp";
		}

		SessionUtils.getSessionWarenkorb(req); // ensure wk is in session
		req.getRequestDispatcher(forward).forward(req, resp);
	}
}
